<?php
namespace app\api\controller;

use app\common\controller\Common;
use app\api\model\User as UserModel;
use think\Validate;

class User extends Common
{
    public function login()
    {
        $this->checkRequest('post');
        $validate = new Validate([
            'email' => 'require|email',
            'password'  => 'require|max:16|min:6',
        ]);
        $data = [
            'email' => trim(input('post.email')),
            'password' => trim(input('post.password')),
        ];
        if (!$validate->check($data)) {
            error($validate->getError(),403);
        }
        return UserModel::login($data['email'], $data['password']);
    }

    public function register() {
        $this->checkRequest('post');
        $request = request();
        $validate = new Validate([
//            'nickname' => 'require|length:2,16|regex:^[A-Za-z0-9]+$',
            'email' => 'require|email',
            'password'  => 'require|max:16|min:6',
            're_password'  => 'require|confirm:password',
        ]);
        $data = [
            'nickname' => trim(input('post.nickname')),
            'email' => trim(input('post.email')),
            'password' => trim(input('post.password')),
            're_password' => trim(input('post.re_password')),
        ];
        if (!$validate->check($data)) {
            error($validate->getError(),412);
        }

        return UserModel::register($data['email'], $data['password'], $data['nickname']);
    }
}
